import RadioButton from './RadioButton';

const {ccclass, property} = cc._decorator;

type rb = RadioButton;


@ccclass
export default class RadioGroupMgr extends cc.Component{

    groups: {[key: number]: rb[]};

    init(){
        this.groups = {};
    }

    add(radioButton: rb){
        let groupId = radioButton.groupId;
        let buttons = this.groups[groupId];
        if(buttons == null){
            buttons = [];
            this.groups[groupId] = buttons;
        }
        this.groups[groupId].push(radioButton);
    }

    del(radioButton: rb){
        let groupId = radioButton.groupId;
        let buttons = this.groups[groupId];
        if(buttons == null){
            return;
        }

        const idx = buttons.indexOf(radioButton);
        if(idx != -1){
            buttons.splice(idx, 1);
        }
        if(buttons.length == 0){
            delete this.groups[groupId];
        }
    }

    check(radioButton: rb){
        let groupId = radioButton.groupId;
        let buttons = this.groups[groupId];
        if(buttons == null){
            return;
        }

        buttons.map((btn) => {
            if(btn == radioButton){
                btn.check(true);
            }
            else{
                btn.check(false);
            }
        });
    }
}